package com.asset.inventory.viewModel

import android.util.Log
import androidx.constraintlayout.solver.GoalRow
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.asset.inventory.base.BaseApp
import com.asset.inventory.base.BaseViewModel
import com.asset.inventory.constant.InventoryState
import com.asset.inventory.manager.ConfigInfoManager
import com.asset.inventory.manager.RfidManager
import com.asset.inventory.model.*
import com.asset.inventory.network.HttpUtils
import com.asset.inventory.network.RequestObserver
import com.asset.inventory.network.RxScheduler
import com.asset.inventory.utils.FileUtils
import com.google.gson.Gson

/**
 *    @author : sibb
 *    date   : 21-3-16
 *    desc   : 资产盘点记录详情
 */
open class AssetInventoryDetailViewModel: BaseViewModel() {

    var isStartScan = ObservableField<Boolean>(false)

    var isReadRfid = ObservableField<Boolean>(false)

    var offlineModel: OfflineModel? = null

    var currentTaskId = 0L

    val isModifySuccess = MutableLiveData<Boolean>()

    val isCommitSuccess = MutableLiveData<Boolean>()

    var mTaskId = 0L


    fun observerCommitStatus() = isCommitSuccess

    fun observerModifyStatus() = isModifySuccess

    private val taskDetailLiveData = MutableLiveData<MutableList<TaskDetailBean.Detail>>()

    fun observerData() = taskDetailLiveData

    private val isShowLoading = MutableLiveData<Boolean>()


    fun loadingLiveData(): MutableLiveData<Boolean> = isShowLoading

    fun setTaskId(taskId: Long) {
        mTaskId = taskId
    }

    fun scanClick(){
        isStartScan.get().let {
            isStartScan.set(!it!!)
            if(isStartScan.get()!!){
                isReadRfid.set(false)
            }

        }


    }

    fun rfidClick(){
        isReadRfid.get().let {
            isReadRfid.set(!it!!)
            if(isReadRfid.get()!!){
                isStartScan.set(false)
            }

        }

    }

    fun commitDataToServer(ids: List<Long>){
        isShowLoading.postValue(true)
        HttpUtils.instance.commitList(ids).compose(RxScheduler.io_main()).subscribe(object: RequestObserver<ModifyAssetsModel>{
            override fun onSuccess(t: ModifyAssetsModel) {
                if(t.status == "success"){
                    isCommitSuccess.postValue(true)
                }else{
                    isCommitSuccess.postValue(false)
                }
                isShowLoading.postValue(false)
            }

            override fun onFaile(e: Throwable) {
                isCommitSuccess.postValue(false)
                isShowLoading.postValue(false)

            }
        })
    }

   private var waitCount = 0

    fun getOffWaitCount(): Int = waitCount

    private var finishCount = 0

    fun getOffFinishCount(): Int = finishCount

    /**
     * 保存数据到SD卡
     */
    fun saveDataToSD(id: Long, state: String){
         waitCount = 0
         finishCount = 0
        //读取SD卡任务文件
        val fileContent = FileUtils.getContentFromSdcard()
        fileContent?.let {
            offlineModel =  Gson().fromJson(fileContent, OfflineModel::class.java)
            if(offlineModel != null && offlineModel?.data != null){
                for(task in offlineModel?.data!!){
                     if(task.id == mTaskId && task.dutyResults != null){
                        for(dutyResult in task.dutyResults){
                            if(dutyResult.id == id){
                                dutyResult.dutyResultStatus = state
                            }
                            if(dutyResult.dutyResultStatus == InventoryState.STATE_WAIT){
                                waitCount++
                            }else if(dutyResult.dutyResultStatus == InventoryState.STATE_EQUALITY || dutyResult.dutyResultStatus == InventoryState.STATE_LOSS){
                                finishCount++
                            }
                        }
                         task.dutyResultDoneCount = finishCount
                         task.dutyResultWaitCount = waitCount
                    }
                }
               val data =  Gson().toJson(offlineModel)
                FileUtils.write2File(data)
                isModifySuccess.postValue(true)
                isShowLoading.postValue(false)
            }
        }
    }


    /**
     * 保存数据扫描所有数据到SD卡
     */
    fun saveDatasToSD(ids: MutableList<Long>, state: String){
        isShowLoading.postValue(true)
        waitCount = 0
        finishCount = 0
        //读取SD卡任务文件
        val fileContent = FileUtils.getContentFromSdcard()
        fileContent?.let {
            offlineModel =  Gson().fromJson(fileContent, OfflineModel::class.java)
            if(offlineModel != null && offlineModel?.data != null){
                for(task in offlineModel?.data!!){
                    if(task.id == mTaskId && task.dutyResults != null){
                        for(dutyResult in task.dutyResults){
                            if(ids.contains(dutyResult.id)){
                                dutyResult.dutyResultStatus = InventoryState.STATE_EQUALITY
                            }
                            if(dutyResult.dutyResultStatus == InventoryState.STATE_WAIT){
                                waitCount++
                            }else if(dutyResult.dutyResultStatus == InventoryState.STATE_EQUALITY || dutyResult.dutyResultStatus == InventoryState.STATE_LOSS){
                                finishCount++
                            }
                        }
                        task.dutyResultDoneCount = finishCount
                        task.dutyResultWaitCount = waitCount
                    }
                }
                val data =  Gson().toJson(offlineModel)
                FileUtils.write2File(data)
                isModifySuccess.postValue(true)
                isShowLoading.postValue(false)
            }
        }
    }


    fun uploadState(id: Long, state: String){
        isShowLoading.postValue(true)
        if(BaseApp.instance.isOnlineModel){
            HttpUtils.instance.putState(id,state).compose(RxScheduler.io_main()).subscribe(object: RequestObserver<Response>{
                override fun onSuccess(t: Response) {
                    if(t.status == "success"){
                        isModifySuccess.postValue(true)
                    }else{
                        isModifySuccess.postValue(false)
                    }
                    isShowLoading.postValue(false)
                }

                override fun onFaile(e: Throwable) {
                    isModifySuccess.postValue(false)
                    isShowLoading.postValue(false)

                }
            })
        }else{
            saveDataToSD(id,state)
        }
    }


    fun getTaskDetail(id: Long){
        isShowLoading.postValue(true)
        currentTaskId = id
        if(BaseApp.instance.isOnlineModel){
            HttpUtils.instance.getTaskDetail(id).compose(RxScheduler.io_main()).subscribe(object: RequestObserver<TaskDetailBean> {
                override fun onSuccess(t: TaskDetailBean) {
                    if(t.status == "success"){
                        taskDetailLiveData.postValue(t.data)
                    }else{
                        showToast("数据请求失败")
                    }
                    isShowLoading.postValue(false)

                }

                override fun onFaile(e: Throwable) {
                    showToast("数据请求失败")
                    isShowLoading.postValue(false)
                    if (BaseApp.instance.isTest){
                        //todo 测试代码
                        testTaskDetal()
                    }

                }

            })
        }else{
            //读取SD卡任务文件
            val fileContent = FileUtils.getContentFromSdcard()
            fileContent?.let {
                offlineModel =  Gson().fromJson(fileContent, OfflineModel::class.java)
                if(offlineModel != null && offlineModel?.data != null){
                    offlineModel?.availableUsers?.let { it1 -> ConfigInfoManager.saveOrgInfo(it1) }
                    offlineModel?.availableLocations?.let {
                        it -> ConfigInfoManager.saveLocationInfo(it)
                    }
                    for(task in offlineModel?.data!!){
                        if(task.id == id){
                            taskDetailLiveData.postValue(task.dutyResults)
                        }
                    }

                }
            }
            isShowLoading.postValue(false)
        }
    }

    fun testTaskDetal(){
        val testJson = "{\n" +
                "    \"status\": \"success\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"id\": 1218,\n" +
                "            \"createTime\": \"2021-04-07 00:08:23\",\n" +
                "            \"updateTime\": \"2021-04-07 00:08:23\",\n" +
                "            \"name\": \"接入路由器\",\n" +
                "            \"code\": \"KJ1190202020629\",\n" +
                "            \"type\": \"1190202020000\",\n" +
                "            \"contractNo\": null,\n" +
                "            \"locationCode\": null,\n" +
                "            \"locationName\": null,\n" +
                "            \"status\": \"idle\",\n" +
                "            \"userId\": \"zhangzhenhua\",\n" +
                "            \"userName\": \"张振华\",\n" +
                "            \"orgId\": \"kj_zybzb\",\n" +
                "            \"orgName\": \"资源保障部\",\n" +
                "            \"updateUserId\": null,\n" +
                "            \"updateUserName\": null,\n" +
                "            \"updateOrgCode\": null,\n" +
                "            \"updateOrgName\": null,\n" +
                "            \"updateLocationCode\": null,\n" +
                "            \"updateLocationName\": null,\n" +
                "            \"note\": null,\n" +
                "            \"dutyResultStatus\": \"wait\",\n" +
                "            \"dutyId\": 5,\n" +
                "            \"dutyName\": \"路由器盘点\",\n" +
                "            \"planName\": \"33322\",\n" +
                "            \"serialnumber\": \"BANGYNGY0000\"\n" +
                "        }\n" +
                "    ]\n" +
                "}"
        val testData = Gson().fromJson(testJson,TaskDetailBean::class.java)
        taskDetailLiveData.postValue(testData.data)

    }

}